import {deleteMsgApi, editMsgApi, sendMsgApi} from "@/api/message.js";
import {useSocket} from "@/socket.js";
import {showToast} from "@/components/toasts/LoginRegToast.js";
import Login from "@/pages/login.vue";
export const messageService = () => {
    const socket = useSocket()
    const sendMessage = async (msgData) => {
        const formData = new FormData()
        Object.entries(msgData).forEach(([key, value]) => {
            if (key === 'file' && Array.isArray(value)) {
                value.forEach(file => {
                    formData.append('file', file);
                });
            } else if (key === 'audio' && value instanceof Blob) {
                formData.append('audio', value);
            } else if (value !== null && value !== undefined) {
                formData.append(key, value);
            }
        });
        const res = await sendMsgApi(formData, (progressEvent)=> {
            console.log(Math.round(progressEvent.loaded * 100) / progressEvent.total)
            msgData.progress = Math.round(progressEvent.loaded * 100) / progressEvent.total
        })
        if (res.status === 200 && res.data.last_id) {
            msgData.id = res.data.last_id
            if (res.data.filenames) {
                msgData.filenames = res.data.filenames
                msgData.mimeType = res.data.mimeType
                msgData.file.length = 0
            }
            console.log(msgData)
            console.log(res.data.last_id)

            console.log()
            socket.emit("chat message", msgData)

            return true
        } else {
            return false
        }
    }

    const updateEditedMsg = async (incomingFields) => {
        const {content, msgId} = incomingFields
        const res = await editMsgApi(msgId, content)
        if (res.status === 200) {
            socket.emit('update message', incomingFields)
            console.log(incomingFields)
            return true
        } else {
            return false
        }
    }

    const deleteMsg = async (msgId, chatId) => {
        if (msgId) {
            const res = await deleteMsgApi(msgId)
            if (res.status === 200) {
                console.log(res.data)
                socket.emit('delete message', {msgId, chatId})
                return true
            } else {
                showToast('error', res.data.msg)
                return false
            }
        }
    }

    return {
        sendMessage,
        updateEditedMsg,
        deleteMsg
    }
}